package cn.core.tool.event;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.springframework.context.ApplicationEvent;

/**
 * 全局数据传输事件<br>
 * 使用Gson进行字符串和对象相互转化<br>
 * 1 模块之间需要相互引用时使用<br>
 * 2 模块之间不能强制依赖时使用<br>
 */
public class CoreDataEvent extends ApplicationEvent {

  private static final long serialVersionUID = 1L;

  private final Gson gson = new GsonBuilder().serializeNulls().create();

  protected String eventKey;

  protected String param;

  protected String data;

  public CoreDataEvent() {
    super("CoreDataEvent");
  }

  public CoreDataEvent(String eventKey) {
    this();
    this.eventKey = eventKey;
  }

  public CoreDataEvent(String eventKey, String param) {
    this();
    this.eventKey = eventKey;
    this.param = param;
  }

  public CoreDataEvent(String eventKey, Object o) {
    this();
    this.eventKey = eventKey;
    this.param = gson.toJson(o);
  }

  public String getEventKey() {
    return eventKey;
  }

  public CoreDataEvent setEventKey(String eventKey) {
    this.eventKey = eventKey;
    return this;
  }

  public String getParam() {
    return param;
  }

  public <T> T getParam(TypeToken<T> o) {
    return gson.fromJson(param, o.getType());
  }

  public CoreDataEvent setParam(String param) {
    this.param = param;
    return this;
  }

  public CoreDataEvent setParam(Object o) {
    this.param = gson.toJson(o);
    return this;
  }

  public String getData() {
    return data;
  }

  public <T> T getData(TypeToken<T> o) {
    return gson.fromJson(data, o.getType());
  }

  public CoreDataEvent setData(String data) {
    this.data = data;
    return this;
  }

  public CoreDataEvent setData(Object o) {
    this.data = gson.toJson(o);
    return this;
  }

}
